package bookstudytest.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Lee
 * @Date: 2018/6/21 15:24
 * @Description: socket服务器端
 */
public class SocketServerDemo {
    public static void main(String[] args) {
        ServerSocket server = null;
        Socket socket = null;
        InputStream inputStream = null;
        String a = "";
        byte[] c = new byte[1024];
        OutputStream outputStream = null;
        BufferedReader bufferedReader = null;
        InputStreamReader reader = null;
        try {
            //监听指定端口
            server = new ServerSocket(9553);
            //收到客户端请求，创建一个socket对象
            socket = server.accept();
            //得到socket的输入字节流
            inputStream = socket.getInputStream();
            //字节流转字符流
            reader = new InputStreamReader(inputStream);
            //缓冲字节流
            bufferedReader = new BufferedReader(reader);
            //每执行一次readLine就读出一行数据
            while ((a = bufferedReader.readLine()) != null) {
                System.out.println(a);
            }

//            while (bf.read())
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            //获得输出字节流
            outputStream = socket.getOutputStream();
            //转字符流
            PrintWriter printWriter = new PrintWriter(outputStream);
            //输出字符
            printWriter.write("This is server ! over!");
            //刷新字符流
            printWriter.flush();
            //关闭资源
            printWriter.close();
            outputStream.close();
            bufferedReader.close();
            reader.close();
            inputStream.close();


        } catch (IOException ioe) {

        }

    }
}
